<template>
  <view class="vocabulary-container">
    <view class="vocabulary-wrapper">
      <view class="vocabulary-row" v-for="(item, index) in vocabulary" :key="index + item.title">
        <view class="row-title">{{ item.title }}</view>
        <view class="row-desc">
          <image class="desc-icon" src="https://rwstatic.tentons.cn/web/Lesson/images/vocabulary-icon.png" />
          <view class="desc-sentence" v-for="(val, inx) in item.sentence" :key="index + inx + val.sentence">
            <rich-text :nodes="handleSetSentence(val.sentence)"></rich-text>
            <text class="translate">{{ val.translate }}</text>
          </view>
        </view>
        <view class="h15"></view>
        <view class="row-tag">{{ index + 1 }}</view>
      </view>
      <view class="vocabulary-line"></view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from "vue";

type TVocabulary = {
  title: string;
  sentence: {
    sentence: string;
    translate: string;
  }[];
};

const vocabulary = ref<TVocabulary[]>([]);

const handleInit = (data: TVocabulary[]) => {
  vocabulary.value = data;
};

const handleSetSentence = (sentence: string) => {
  let childrenNodes: any[] = [];
  const sentenceParts = sentence.split(" ");

  sentenceParts.forEach((item) => {
    const regex = /(<b>.*?<\/b>)(.*)/;

    if (regex.test(item)) {
      const match = item.match(regex) || ["", ""];
      const content = match[1]; // 匹配到的<b>...</b>内容
      const other = match[2]; // 匹配到的后续字符

      childrenNodes.push({
        name: "span",
        attrs: {
          class: "rich-text_sentence_red",
        },
        children: [
          {
            type: "text",
            text: other.length ? `${content.replace(/<\/?b>/g, "")}` : `${content.replace(/<\/?b>/g, "")} `,
          },
        ],
      });
      if (other.length) {
        childrenNodes.push({
          type: "text",
          text: `${other}`,
        });
      }
    } else {
      childrenNodes.push({
        type: "text",
        text: `${item} `,
      });
    }
  });

  return [
    {
      name: "div",
      attrs: {
        class: "rich-text_sentence",
      },
      children: childrenNodes,
    },
  ];
};

defineExpose({
  handleInit,
});
</script>

<style scoped lang="scss">
@import "./common.scss";
</style>

<style lang="scss">
.rich-text_sentence {
  display: inline-block;
  margin-bottom: 0.5rem;
  font-size: 1.5rem;
  font-family: xiaolai;
  line-height: 2.2rem;
  color: $uni-text-color;
}

.rich-text_sentence_red {
  color: $uni-text-color-error;
}
</style>
